<template>
	<view id="page-content">
		<view class="goBack">
			<text class="gobackText" @click="goBack">
				<uni-icons type="left" size="18" color="#3E89FA"></uni-icons>
				返回
			</text>
		</view>
		<view class="findall">
			<view class="feed" v-for="(item, index) in based" :key="index" @click="related(item.id)">
				<view class="find">
					<view class="name">
						<!-- 可考虑添加图片懒加载 -->
						<image class="namepic" :src="item.picUrl" mode=""></image>
						<view class="info">
							<view class="text">
								{{item.title}}
							</view>
							<view class="line"></view>
							<view class="pire">
								{{item.readCount}}
							</view>
						</view>
					</view>
				</view>
				<view class="desc">
					{{item.subtitle}}
				</view>
			</view>
			<!-- 当没有更多数据时显示提示 -->
			<view class="feed" v-if="!hasMore">
				<view class="van-list__finished-text">
					没有更多了
				</view>
			</view>
			<!-- 加载中提示 -->
			<view class="feed" v-if="isLoading">
				<view class="van-list__loading-text">
					加载中...
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		get
	} from '@/lib/http.js';
	import {
		debounce
	} from 'lodash';

	export default {
		data() {
			return {
				based: [],
				page: 1,
				limit: 10,
				isLoading: false, // 加载状态
				windowHeight: 0, // 存储窗口高度
				scrollHeight: 0, // 存储手动计算的 scrollHeight
				hasMore: true // 是否还有更多数据
			};
		},
		onReady() {
			this.$nextTick(() => {
				const query = uni.createSelectorQuery();
				query.select('#page-content').boundingClientRect((rect) => {
					if (rect) {
						this.scrollHeight = rect.height;
					}
				}).exec();
			});
		},
		onLoad() {
			uni.getSystemInfo({
				success: (res) => {
					this.windowHeight = res.windowHeight;
				},
				fail: (err) => {
					console.error('获取系统信息失败', err);
				}
			});
			// 页面加载时获取轮播数据
			this.fetchData(this.page);
		},
		onPageScroll: debounce(function(e) {
			const scrollTop = e.scrollTop;
			console.log('scrollTop:', scrollTop, 'windowHeight:', this.windowHeight, 'scrollHeight:', this
				.scrollHeight);
			// 当有更多数据且满足滚动条件时加载数据
			if (this.hasMore && this.windowHeight && this.scrollHeight && scrollTop + this.windowHeight >= this
				.scrollHeight - 100 && !this.isLoading && this.page < 5) {
				this.isLoading = true;
				this.page++;
				this.fetchData(this.page)
					.finally(() => {
						this.isLoading = false;
					});
			}
		}, 200),
		methods: {
			related(id) {
				uni.navigateTo({
					url: `/pages/topic/topic?id=${id}`
				})
			},
			goBack() {
				uni.navigateBack({
					// 返回层级  如果层级没有那么多就直接跳到首页
					delta: 1
				});
			},
			// 通用的数据请求方法
			fetchData(page) {
				return new Promise((resolve, reject) => {
					const controller = new AbortController();
					const signal = controller.signal;
					const timeoutId = setTimeout(() => {
						controller.abort();
						console.error('请求超时');
						uni.showToast({
							title: '请求超时，请检查网络',
							icon: 'none'
						});
						this.hasMore = false;
						reject(new Error('请求超时'));
					}, 5000); // 设置超时时间为 5 秒

					get(`/wx/topic/list?page=${page}&limit=${this.limit}`, {
							signal
						})
						.then((response) => {
							clearTimeout(timeoutId);
							const data = response.data;
							if (data && data.data && data.data.list) {
								const oldLength = this.based.length;
								if (page === 1) {
									this.based = data.data.list;
								} else {
									this.based = this.based.concat(data.data.list);
								}
								// 若新数据为空，说明没有更多数据了
								if (data.data.list.length === 0) {
									this.hasMore = false;
								}
								// 仅当数据长度变化时重新计算 scrollHeight
								if (this.based.length !== oldLength) {
									this.$nextTick(() => {
										const query = uni.createSelectorQuery();
										query.select('#page-content').boundingClientRect((rect) => {
											if (rect) {
												this.scrollHeight = rect.height;
											}
										}).exec();
									});
								}
								resolve();
							} else {
								console.error('返回的数据格式错误');
								uni.showToast({
									title: '数据格式错误',
									icon: 'none'
								});
								this.hasMore = false;
								reject();
							}
						})
						.catch((error) => {
							clearTimeout(timeoutId);
							let errorMessage;
							if (error.response) {
								errorMessage = `请求出错，状态码：${error.response.status}`;
							} else if (error.request) {
								errorMessage = '请求已发送，但没有收到响应';
							} else if (error.name === 'AbortError') {
								return; // 超时导致的取消，已处理提示
							} else {
								errorMessage = '网络错误，请检查网络连接';
							}
							console.error('请求出错', error);
							uni.showToast({
								title: errorMessage,
								icon: 'none'
							});
							this.hasMore = false;
							reject();
						});
				});
			}
		}
	};
</script>

<style>
	/* 引入外部样式文件 */
	@import './top.css';

	/* 加载中提示样式 */
	.van-list__loading-text {
		text-align: center;
		color: #999;
		padding: 10px 0;
	}

	/* 没有更多了提示样式 */
	.van-list__finished-text {
		text-align: center;
		color: #999;
		padding: 10px 0;
	}
</style>